package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.query.ServiceItemQuery;
import cn.wolfcode.car.business.service.IBpmnInfoService;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.business.service.IServiceItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.common.util.Convert;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import jdk.jshell.spi.ExecutionControl;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class ServiceItemServiceImpl implements IServiceItemService {

    @Autowired
    private ServiceItemMapper serviceItemMapper;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private IBpmnInfoService bpmnInfoService;
    @Autowired
    private RuntimeService runtimeService;


    @Override
    public TablePageInfo<ServiceItem> query(ServiceItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<ServiceItem>(serviceItemMapper.selectForList(qo));
    }


    @Override
    public void save(ServiceItem serviceItem) {
        //在进行添加操作时，先判断是不是套餐
        //是套餐需要进行审核，把状态设置为初始化
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage())){
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else{
            //非套餐，把状态设置为默认值:无需审核
            serviceItem.setAuditStatus(ServiceItem.AUDITSTATUS_NO_REQUIRED);
        }
        //添加完成首先需要让该数据为下架状态
        //由于添加页面没有给时间、销售状态、审核状态等值进行填写，需要手动进行赋值或给默认值进行补齐
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(new Date());
        serviceItemMapper.insert(serviceItem);
    }

    @Override
    public ServiceItem get(Long id) {
        return serviceItemMapper.selectByPrimaryKey(id);
    }


    @Override
    public void update(ServiceItem serviceItem) {
        //当数据进行更新操作时，如果页面收集的数据只是部分数据，此时更新操作时需要考虑页面数据缺失问题
        //有3种解决方案
        //1.在sql中将不需要进行更新的字段进行删除(常用)
        //2.先查，在替换，最后再更新

        //如果是上架状态，不能进行修改
        ServiceItem st = this.get(serviceItem.getId());
        if(ServiceItem.SALESTATUS_ON.equals(st.getSaleStatus())){
            throw new BusinessException("该服务项在上架中，不允许修改");
        }
        //如果是套餐，且没有审核通过，不能进行修改
        if(ServiceItem.CARPACKAGE_YES.equals(st.getCarPackage())
        && ServiceItem.AUDITSTATUS_AUDITING.equals(st.getAuditStatus())){
            throw new BusinessException("审核中，不能进行修改");
        }
        //如果是下架状态,并且套餐，且审核通过了，再重新进行编辑，需要把审核状态设为初始状态
        if(ServiceItem.CARPACKAGE_YES.equals(st.getCarPackage())
        && ServiceItem.AUDITSTATUS_APPROVED.equals(st.getAuditStatus())){
            st.setAuditStatus(ServiceItem.AUDITSTATUS_INIT);
        }else {
            //是什么审核状态就返回什么审核状态
            serviceItem.setAuditStatus(st.getAuditStatus());
        }
        //把销售状态设置为下架
        serviceItem.setSaleStatus(ServiceItem.SALESTATUS_OFF);
        serviceItem.setCreateTime(serviceItem.getCreateTime());
        //3.通过动态sql实现
        serviceItemMapper.updateByPrimaryKey(serviceItem);
    }

    @Override
    public void deleteBatch(String ids) {
        Long[] dictIds = Convert.toLongArray(ids);
        for (Long dictId : dictIds) {
            serviceItemMapper.deleteByPrimaryKey(dictId);
        }
    }

    @Override
    public List<ServiceItem> list() {
        return serviceItemMapper.selectAll();
    }

    @Override
    public void saleOn(Long id) {
        ServiceItem serviceItem = this.get(id);
        //数据处于上架状态,再点击上架，抛出异常.
        if(ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())){
            throw new BusinessException("服务单项已经处于上架状态");
        }
        //如果是套餐,并且不是审核通过的状态，是不能上架的，抛出异常.
        if(ServiceItem.CARPACKAGE_YES.equals(serviceItem.getCarPackage()) &&
        !ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("套餐审核通过才可以进行上架");
        }
        //非套餐，可以直接进行上架
        //通过id把状态修改为上架
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_ON);
    }

    @Override
    public void saleOff(Long id) {
        //通过id把状态修改为下架
        serviceItemMapper.changeSaleStatus(id,ServiceItem.SALESTATUS_OFF);
    }

    @Override
    public void startAudit(Long serviceItemId, Long bpmnInfoId, Long director, Long finance, String info) {
        //通过服务单项明细获取单项明细对象,进行合理性校验
        //(只有处于下架状态，是套餐且审核状态为初始化或审核拒绝才可发起审核)
        ServiceItem serviceItem = serviceItemMapper.selectByPrimaryKey(serviceItemId);
        if(ServiceItem.SALESTATUS_ON.equals(serviceItem.getSaleStatus())
        || ServiceItem.CARPACKAGE_NO.equals(serviceItem.getCarPackage())
        || ServiceItem.AUDITSTATUS_AUDITING.equals(serviceItem.getAuditStatus())
        || ServiceItem.AUDITSTATUS_APPROVED.equals(serviceItem.getAuditStatus())
        || ServiceItem.AUDITSTATUS_NO_REQUIRED.equals(serviceItem.getAuditStatus())){
            throw new BusinessException("参数异常");
        }
        //创建CarPackageAudit对象
        CarPackageAudit audit = new CarPackageAudit();
        audit.setServiceItemId(serviceItemId);
        audit.setServiceItemInfo(serviceItem.getInfo());
        audit.setServiceItemPrice(serviceItem.getDiscountPrice());
        audit.setCreator(ShiroUtils.getUser().getUserName());
        audit.setBpmnInfoId(bpmnInfoId);
        audit.setInfo(info);
        audit.setAuditorId(director);
        audit.setCreateTime(new Date());
        audit.setServiceItemName(serviceItem.getName());
        //启动流程实例,绑定业务标识,并把map也一并传入
        BpmnInfo bpmnInfo = bpmnInfoService.get(bpmnInfoId);
        Map<String,Object> map = new HashMap<>();
        map.put("discountPrice",serviceItem.getDiscountPrice().longValue());
        if(director != null){
            map.put("director",director);
        }
        if(finance != null){
            map.put("finance",finance);
        }
        carPackageAuditService.save(audit);
        //1.1获取流程定义的key
        String processKey = bpmnInfo.getActProcessKey();
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processKey, String.valueOf(audit.getId()), map);
        audit.setInstanceId(processInstance.getId());
        carPackageAuditService.update(audit);
        //将服务单项明细的套餐状态更改为审核中
        serviceItemMapper.changeAuditStatus(serviceItemId,ServiceItem.AUDITSTATUS_AUDITING);
    }

    @Override
    public void changeAuditStatus(Long serviceItemId, Integer status) {
        serviceItemMapper.changeAuditStatus(serviceItemId,status);
    }
}
